package com.jvyou.app.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jvyou.app.common.constants.BaseConstants;
import com.jvyou.app.common.enums.HttpCodeEnum;
import com.jvyou.app.common.exception.AppException;
import com.jvyou.app.ds.domain.entity.Student;
import com.jvyou.app.ds.mapper.StudentMapper;
import com.jvyou.app.ds.utils.login.LoginContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.jvyou.app.ds.domain.entity.AnswerSession;
import com.jvyou.app.ds.service.AnswerSessionService;
import com.jvyou.app.ds.mapper.AnswerSessionMapper;


/**
 * (AnswerSesson)表服务实现类
 *
 * @author 橘柚
 * @since 2025-04-21 20:38:17
 */
@Service("answerSessonService")
@RequiredArgsConstructor
public class AnswerSessionServiceImpl extends ServiceImpl<AnswerSessionMapper, AnswerSession> implements AnswerSessionService {

    private final StudentMapper studentMapper;

    @Override
    public AnswerSession addAnswerSession(AnswerSession answerSession) {
        // 1. 查询学生信息
        Long userId = LoginContext.getUserId();
        Student student = studentMapper.getByUser(userId);
        if (student == null) {
            throw new AppException(HttpCodeEnum.DATA_NOT_EXIST,"学员信息异常，查询不到学员信息");
        }
        // 2. 取消所有的isCurrent
        LambdaUpdateWrapper<AnswerSession> uw = new LambdaUpdateWrapper<>();
        uw.eq(AnswerSession::getStudentId, student.getId());
        uw.eq(AnswerSession::getSubject, answerSession.getSubject());
        uw.eq(AnswerSession::getLicenseType, answerSession.getLicenseType());
        uw.set(AnswerSession::getIsCurrent, BaseConstants.NO);
        this.update(uw);
        answerSession.setStudentId(student.getId());
        answerSession.setIsCurrent(BaseConstants.YES);
        this.save(answerSession);
        return answerSession;
    }
}
